package com.th.cash.th2.product

import android.text.Editable
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import com.lxj.xpopup.XPopup
import com.th.basemodel.base.BaseVDBLazyLoadingFragment2
import com.th.basemodel.ext.bindData
import com.th.basemodel.ext.divider
import com.th.basemodel.ext.dp2px
import com.th.basemodel.ext.itemClick
import com.th.basemodel.ext.vertical
import com.th.cash.storage.LocalSetting
import com.th.resmodel.R

abstract class VerifyBaseFragment<VB : ViewDataBinding> : BaseVDBLazyLoadingFragment2<VB>() {

    open var type = 0

    val mDataList = mutableListOf<VerifyItemResponse>()

    fun getPid(): String {
        return (activity as ProductActivity).pid
    }

    fun setOid(oid: String) {
        (activity as ProductActivity).oid = oid
    }

    fun back(type: Int) {
        (activity as ProductActivity).showRetentionPopup(type)
    }

    fun nextPage(path: String,boolean: Boolean = true) {
        if (TextUtils.isEmpty(path)) {
            if (LocalSetting.userAdult && boolean) {
                (activity as ProductActivity).loadFragment("info")
            } else {
                (activity as ProductActivity).getOrderUrl()
            }
        } else {
            (activity as ProductActivity).loadFragment(path)
        }
    }

    fun initVerifyAdapter(recyclerView: RecyclerView) {
        recyclerView.vertical()
            .divider(
                color = ContextCompat.getColor(requireContext(), R.color.white),
                size = dp2px(10f)
            )
            .bindData(mDataList, R.layout.item_verify) { holder, item, position ->
                // 设置标题
                holder.setText(R.id.tvVerifyTitle, item.fOEJfxDMilchSvtaQHn)

                // 获取控件对象
                val tvVerifyContent = holder.getView<TextView>(R.id.tvVerifyContent)
                val ivVerifySelect = holder.getView<ImageView>(R.id.ivVerifySelect)
                val etVerifyContent = holder.getView<EditText>(R.id.etVerifyContent)

                val textWatcher = object : TextWatcher {
                    override fun beforeTextChanged(
                        s: CharSequence,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {
                    }

                    override fun onTextChanged(
                        s: CharSequence,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                    }

                    override fun afterTextChanged(s: Editable) {
                        if (TextUtils.isEmpty(s.toString())) {
                            item.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc = ""
                        } else {
                            item.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc = s.toString()
                        }
                    }
                }

                etVerifyContent.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
                    if (hasFocus) {
                        etVerifyContent.addTextChangedListener(textWatcher)
                    } else {
                        etVerifyContent.removeTextChangedListener(textWatcher)
                    }
                }

                // 根据lheDxlwSavineQFqzfNN字段判断显示类型
                val isSelectType = item.lheDxlwSavineQFqzfNN == "EWSPDAUWJBTNNIH" ||
                        item.lheDxlwSavineQFqzfNN == "YUYLYMWKBSOONDG"

                // 设置可见性
                tvVerifyContent.visibility = if (isSelectType) View.VISIBLE else View.GONE
                ivVerifySelect.visibility = if (isSelectType) View.VISIBLE else View.GONE
                etVerifyContent.run {
                    visibility = if (isSelectType) View.GONE else View.VISIBLE

                    inputType = if (item.lheDxlwSavineQFqzfNN == "IUHJHCIUDSNCY") {
                        InputType.TYPE_CLASS_NUMBER
                    } else {
                        InputType.TYPE_CLASS_TEXT
                    }
                }

                // 设置内容文本
                if (item.lheDxlwSavineQFqzfNN == "EWSPDAUWJBTNNIH") {
                    // 如果是选择类型，查找匹配的选项
                    val selectedValue = item.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
                    val matchedOption = item.hrbuvGdRemiseQqQMBqZ.find { option ->
                        option.wQFohwTEnormityOlsvnWX == selectedValue
                    }

                    // 显示匹配的选项文本或默认文本
                    val displayText =
                        matchedOption?.LOtUxphBluesmanCElYqFg ?: item.ODymYqTSuperwaterAVPVdvk
                    holder.setText(R.id.tvVerifyContent, displayText)
                } else if (item.lheDxlwSavineQFqzfNN == "YUYLYMWKBSOONDG") {
                    holder.setText(
                        R.id.tvVerifyContent,
                        item.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
                    )
                } else {
                    // 如果是输入类型，直接显示PxGEecSAntiwarMrDXISc的值
                    holder.setText(
                        R.id.etVerifyContent,
                        item.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
                    )
                }
            }
            .itemClick<VerifyItemResponse> { data, _, position ->
                val item = data[position]
                when (item.lheDxlwSavineQFqzfNN) {
                    "EWSPDAUWJBTNNIH" -> {
                        selectItem(recyclerView, item, true)
                    }

                    "YUYLYMWKBSOONDG" -> {
                        selectData(recyclerView, item)
                    }
                }
            }


    }

    fun selectItem(recyclerView: RecyclerView, bean: VerifyItemResponse, fieldChange: Boolean) {
        if (bean.hrbuvGdRemiseQqQMBqZ.isEmpty()) {
            return
        }

        val itemList = bean.hrbuvGdRemiseQqQMBqZ.map {
            SingleSelectionPopup.SelectItem(
                it.LOtUxphBluesmanCElYqFg,
                it.wQFohwTEnormityOlsvnWX,
                TextUtils.equals(
                    it.wQFohwTEnormityOlsvnWX,
                    bean.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
                )
            )
        }

        XPopup.Builder(requireContext())
            .asCustom(
                SingleSelectionPopup(
                    requireContext(),
                    bean.fOEJfxDMilchSvtaQHn,
                    itemList
                ).run {
                    clickListener = { position ->
                        if (fieldChange) {
                            bean.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc = itemList[position].id
                        } else {
                            bean.PxGEecSAntiwarMrDXISc.TnLNYShCockleDaANaRv = itemList[position].id
                        }

                        recyclerView.adapter?.notifyItemChanged(mDataList.indexOf(bean))

                        autoShowSelectPopup(recyclerView, fieldChange, mDataList.indexOf(bean) + 1)
                    }

                    this
                })
            .show()
    }

    private fun selectData(recyclerView: RecyclerView, bean: VerifyItemResponse) {
        XPopup.Builder(requireContext())
            .asCustom(
                DateSelectionPopup(
                    requireContext(),
                    bean.fOEJfxDMilchSvtaQHn,
                    bean.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
                ).run {
                    clickListener = { time ->
                        bean.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc = time
                        recyclerView.adapter?.notifyItemChanged(mDataList.indexOf(bean))

                        autoShowSelectPopup(recyclerView, false, mDataList.indexOf(bean) + 1)
                    }
                    this
                })
            .show()
    }

    private fun autoShowSelectPopup(
        recyclerView: RecyclerView,
        fieldChange: Boolean,
        selectIndex: Int
    ) =
        recyclerView.postDelayed({
            if (selectIndex >= mDataList.size) {
                return@postDelayed
            }

            var dto = mDataList[selectIndex]


            val value = if (fieldChange) {
                dto.PxGEecSAntiwarMrDXISc.PxGEecSAntiwarMrDXISc
            } else {
                dto.PxGEecSAntiwarMrDXISc.TnLNYShCockleDaANaRv
            }


            if (!TextUtils.isEmpty(value)) {
                return@postDelayed
            }

//        (binding.rvQuestion.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(nextIndex, 0)

            val smoothScroller = object : LinearSmoothScroller(requireContext()) {
                override fun getVerticalSnapPreference(): Int {
                    return SNAP_TO_START
                }
            }

            smoothScroller.targetPosition = selectIndex
            recyclerView.layoutManager?.startSmoothScroll(smoothScroller);


            when (dto.lheDxlwSavineQFqzfNN) {
                "EWSPDAUWJBTNNIH", "YUYLYMWKBSOONDG" -> {
                    val childAt = recyclerView.layoutManager!!.findViewByPosition(selectIndex)
                    childAt?.performClick()
                }

                else -> {
                }
            }
        }, 200)
}